<!--
 * @Author: jianfanfan 是是是
 * @Date: 2025-09-12 13:54:02
 * @LastEditors: jianfanfan 是是是
 * @LastEditTime: 2025-09-16 14:20:51
 * @FilePath: \nest-project\index.html
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
-->
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport"
        content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <script
        src="https://unpkg.com/axios@0.24.0/dist/axios.min.js"></script>
</head>

<body>
    <input id="fileInput" type="file" />
    <script>
        const fileInput = document.querySelector('#fileInput')

        const chunkSize = 20 * 1024

        fileInput.onchange = async function () {
            const file = fileInput.files[0]
            if (!file) return

            console.log('开始上传文件:', file.name, '大小:', file.size)

            const chunks = []
            let startPos = 0
            while (startPos < file.size) {
                chunks.push(file.slice(startPos, startPos + chunkSize))
                startPos += chunkSize
            }

            const randomStr = Math.random().toString().slice(2, 8)
            const fileName = randomStr + '_' + file.name

            console.log('分片数量:', chunks.length)

            try {
                // 上传所有分片
                const tasks = chunks.map((chunk, index) => {
                    const data = new FormData()
                    data.set('name', fileName + '-' + index)
                    data.append('files', chunk)
                    return axios.post('http://localhost:3000/upload', data)
                })

                await Promise.all(tasks)
                console.log('所有分片上传完成，开始合并...')

                // 合并文件
                const response = await axios.get('http://localhost:3000/merge?name=' + fileName)
                console.log('文件合并结果:', response)

                if (response.data.success) {
                    alert('文件上传成功！')
                } else {
                    alert('文件合并失败：' + response.data.message)
                }
            } catch (error) {
                console.error('上传失败:', error)
                alert('上传失败，请重试')
            }
        }
    </script>
</body>

</html>